import axios from 'axios'
import store from '@/store'
import router from '@/router/pc'
import { Message } from 'iview'
import { getToken } from '@/utils/auth'

const service = axios.create({
    baseURL: '/api',//接口地址
    withCredentials: false,//允许携带Cookie
    timeout: 5000//请求超时时间
})

service.interceptors.request.use(
    config => {
        var token = getToken()
        if (token) {
            config.headers['Authorization'] = token
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        const res = response.data
        if (response.status !== 200) {
            Message.error(res.message || 'Error', 5)
            if (res.status === 401) {
                store.dispatch('resetToken').then(() => {
                    location.reload()
                })
            }
            return Promise.reject(new Error(res.message || 'Error'))
        }
        else {
            return res
        }
    },
    error => {
        //非法token，进入非法页面
        if (error.response.status === 502) {
            router.push({path:'/'})
            return
        }
        console.log(error)
        Message.error(error.message || 'Error', 5)
        return Promise.reject(error)
    }
)
export default service


